<template>
  <div class="reset-pwd">
    <div class="title" v-if="step === 1">
      <span>安全验证</span>
    </div>
    <div class="title" v-if="step === 2">
      <span>重置密码</span>
    </div>
    <el-form
      v-if="step === 1"
      ref="codeForm"
      :model="codeForm"
      :rules="codeRule"
      class="modify-form"
      autocomplete="on"
      label-position="right"
    >
      <div class="desc">
        我们已经向{{ $route.query.m }}发送了验证码，请注意查收
      </div>
      <el-form-item prop="code">
        <el-input
          key="resetPassword1"
          v-model="codeForm.code"
          maxlength="6"
          placeholder="请输入验证码"
          name="code"
          autocomplete="on"
        >
          <span slot="prefix" class="svg-container">
            <svg-icon name="icon_lock" />
          </span>
          <el-button slot="append" @click="getCode">{{
            sendBtnText
          }}</el-button>
        </el-input>
      </el-form-item>
      <el-button
        v-waves
        :loading="loading"
        type="primary"
        @click="vadCode"
        style="width:100%"
        >校验</el-button
      >
    </el-form>

    <el-form
      v-if="step === 2"
      ref="resetForm"
      :model="resetPasswordForm"
      :rules="resetPasswordRules"
      class="modify-form"
      autocomplete="on"
      label-position="right"
    >
      <el-form-item prop="password">
        <el-input
          key="resetPassword1"
          v-model="resetPasswordForm.password"
          type="password"
          placeholder="请输入密码"
          name="password"
          autocomplete="on"
        >
          <span slot="prefix" class="svg-container">
            <svg-icon name="icon_lock" />
          </span>
        </el-input>
      </el-form-item>

      <el-form-item prop="retype_password">
        <el-input
          key="resetPassword2"
          v-model="resetPasswordForm.retype_password"
          type="password"
          placeholder="请确认密码"
          name="password"
          autocomplete="on"
        >
          <span slot="prefix" class="svg-container">
            <svg-icon name="icon_lock" />
          </span>
        </el-input>
      </el-form-item>

      <el-button
        v-waves
        :loading="loading"
        type="primary"
        style="width:100%; margin-bottom:30px;"
        @click.native.prevent="handleReSetPassword"
        >确认修改</el-button
      >
    </el-form>
    <br />
    <br />
    <div class="color-pr text-center">
      <router-link to="/logon" replace>
        <svg-icon name="arrow1" />
        去登录
      </router-link>
    </div>
  </div>
</template>
<script lang="ts">
/**
 * generate by vscode
 */
import { Component, Vue, Prop } from 'vue-property-decorator'
import { resentEmail, resetPassword } from '@/api/system/users'
import { getResetMsgCode } from '@/api/system/users'
import { Message } from 'element-ui'
const WAIT_TIME = 60
@Component({
  name: 'reset-pwd'
})
export default class resetPwd extends Vue {
  @Prop() someProp?: any
  loading = false
  sending = false
  time = 0
  tid = 0
  token = ''
  step = 1

  codeForm = {
    code: ''
  }
  codeRule = {
    code: [
      {
        required: true,
        len: 6,
        message: '请输入6位验证码',
        trigger: 'blur'
      },
      {
        trigger: 'blur',
        validator(rule: any, value: string, cb: Function) {
          if (/\d{6}/.test(value)) {
            return cb()
          }
          return cb(new Error('请输入6位验证码'))
        }
      }
    ]
  }
  resetPasswordForm = {
    password: '',
    retype_password: ''
  }
  mounted() {
    // this.$nextTick(() => {
    //   // 如果没超过60s
    //   if (this.$route.query.t && this.$route.query.m) {
    //     const t = +this.$route.query.t
    //     const dis = Date.now() - t
    //     console.log(dis)
    //     if (dis < 60 * 1000) {
    //       this.time = Math.floor(dis / 1000)
    //       this.startTimer(false)
    //     }
    //   }
    // })

    this.$nextTick(() => {
      if (this.$route.query.token) {
        // @ts-ignore
        this.token = this.$route.query.token
        this.step = 2
      }
    })
  }
  get resetPasswordRules() {
    return {
      password: [
        {
          required: true,
          trigger: 'blur',
          min: 6,
          message: '请输入至少6位的密码'
        }
      ],
      retype_password: [
        {
          required: true,
          trigger: 'blur',
          validator: (rules: any, val: string, cb: any) => {
            cb(
              val === this.resetPasswordForm.password
                ? undefined
                : new Error('两次密码输入不一致')
            )
          }
        }
      ]
    }
  }

  private async handleReSetPassword() {
    //@ts-ignore
    const form = this.$refs.resetForm as ElForm
    form.validate(async (valid: boolean) => {
      if (!valid) {
        return
      }
      this.loading = true
      try {
        const { data } = await resetPassword(
          Object.assign({ token: this.token }, this.resetPasswordForm)
        )
        await this.$confirm(`密码修改成功,请重新登录。`, '提示', {
          confirmButtonText: '去登录',
          type: 'success',
          showCancelButton: false
        })
        this.$router.replace('/login')
      } catch {
        //
      }
      this.loading = false
    })
  }

  async getCode() {
    this.startTimer()
  }
  // 校验验证码
  async vadCode() {
    //@ts-ignore
    this.$refs.codeForm.validate(async (valid: boolean) => {
      if (!valid) {
        return
      }
      this.loading = true
      try {
        const query: any = {
          method: 'mobile',
          sms_verify_code: this.codeForm.code,
          email_mobile: this.$route.query.m
        }
        const { data } = await resentEmail(query)
        this.token = data.token
        this.step = 2
      } catch {
        //
      }
      this.loading = false
    })
  }
  get sendBtnText() {
    if (this.time !== 0) {
      return WAIT_TIME - this.time + 's'
    }
    return '重新获取'
  }
  async startTimer(isSend: boolean = true) {
    if (this.time !== 0 || this.sending) {
      return
    }
    clearInterval(this.tid)
    this.sending = true
    if (isSend) {
      //@ts-ignore
      await getResetMsgCode(this.$route.query.m)
      Message.success('验证码已发送，请注意查收')
    }
    this.sending = false

    const fn = () => {
      let t = this.time + 1
      if (t >= WAIT_TIME) {
        t = 0
        clearInterval(this.tid)
      }
      this.time = t
    }
    fn()
    //@ts-ignore
    this.tid = setInterval(fn, 1000)
  }
}
</script>
<style lang="scss" scoped>
.reset-pwd {
  width: 380px;
  .desc {
    margin-bottom: 20px;
    color: #666;
    text-align: center;
  }
}
.modify-form {
  margin-top: 40px;
}
</style>
